package com.hushan.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

/**
 * Created by hushan on 2017/5/27.
 */
public class ShiroMain {
    public static void main(String[] args) {
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        SecurityManager securityManager  = factory.getInstance();

        SecurityUtils.setSecurityManager(securityManager);

        // get the currently executing user:
        Subject currentUser = SecurityUtils.getSubject();  //获取当前执行的Subject

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        Session session = currentUser.getSession();
        session.setAttribute("someKey","aValue");

        //判断当前用户是否已认证
        if (!currentUser.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken("hushan", "123456");
            token.setRememberMe(true);

            try {
                currentUser.login(token); //登录
                //if no exception, that's it, we're done!

            }catch (UnknownAccountException uae){
                //username wasn't in the system, show them an error message?

            }catch (IncorrectCredentialsException ice){
                //password didn't match, try again?

            }catch (LockedAccountException lae){
                //account for that username is locked - can't login.  Show them a message?

            }

             //这里有许多不同类别的异常你可以检测到，也可以抛出你自己异常。
            //最好的方式是将普通的失败信息反馈给用户，你总不会希望帮助黑客来攻击你的系统吧


            //登出
            currentUser.logout(); //removes all identifying information and invalidates their session too.

            System.exit(0);
        }
    }
}
